package com.example.demo.service.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: ak
 * @Date: 2020/4/2 22:10
 */
@Slf4j
public class PermissionManger {
    private Map<String,Role> roleMap=new HashMap<>();
    private Role user;
    private Role admin;

    public PermissionManger(){
        //用户和管理员的基础权限配置
        log.info("开始配置基础权限-------------------");
        Permission userHome = new Permission(1, "user:home");
        Permission userComment = new Permission(1, "user:comment");
        Permission userViewQuestion = new Permission(1, "user:viewQuestion");
        Permission userViewForum = new Permission(1, "user:viewForum");
        Permission userView = new Permission(1, "user:publish");
        Permission adminUserAdd = new Permission(1, "admin:userAdd");
        Permission adminUserDle = new Permission(1, "admin:userDle");
        Permission adminUserUpdate = new Permission(1, "admin:userUpdate");
        Permission adminHome = new Permission(1, "admin:home");
        Role admin = new Role(1,"admin");
        Role user = new Role(1,"user");
        admin.add(adminUserAdd);
        admin.add(adminUserDle);
        admin.add(adminUserUpdate);
        admin.add(adminHome);
        user.add(userHome);
        user.add(userComment);
        user.add(userViewQuestion);
        user.add(userViewForum);
        user.add(userView);
        this.admin=admin;
        this.user=user;
        this.addRole(admin.getRoleName(),admin);
        this.addRole(user.getRoleName(),user);
    }
    public void addRole(String roleName,Role role){
        getRoleMap().merge(roleName, role, (role1, role2) -> {
            for (Permission permission : role2.getPermissionSet()) {
                role1.add(permission);
            }
            return null;
        });
        getRoleMap().put(roleName,role);
    }
    public Role getRole(String roleName){
        return getRoleMap().get(roleName);
    }

    public Map<String, Role> getRoleMap() {
        return roleMap;
    }

    public Role getUser() {
        return user;
    }

    public Role getAdmin() {
        return admin;
    }
}
